package com.springfreemwork.tomcat.servlet;

import com.alibaba.fastjson.JSON;
import com.springframework.context.utils.AnnotationUtils;
import com.springframework.context.utils.ScanUtils;
import com.springfreemwork.annotation.Controller;
import com.springfreemwork.annotation.RequestMapping;
import com.springfreemwork.tomcat.ServletHandler;


import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

/**
 * @author gpo12345678@163.com
 * @create 2024-04-07 14:17
 */
public class DefaultServletHandler implements ServletHandler {

	@Override
	public HashMap<String, Servlet> servletMapping(List<Class<?>> classes) {
		HashMap<String, Servlet> result = new HashMap<>();
		for (Class<?> aClass : classes) {
			if (AnnotationUtils.hasAnnotation(aClass,Controller.class)) {
				Method[] methods = aClass.getMethods();
				for (Method method : methods) {
					if(AnnotationUtils.hasAnnotation(aClass,RequestMapping.class)){
						Servlet jsonHttpServlet = new JsonHttpServlet() {
							@Override
							protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
								// 设置内容类型为JSON
								response.setContentType("application/json");
								// 设置字符编码为UTF-8
								response.setCharacterEncoding("UTF-8");
								// 获取PrintWriter对象用于写入响应
								PrintWriter out = response.getWriter();

								BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
								StringBuilder jsonBuilder = new StringBuilder();
								String line;
								while ((line = reader.readLine()) != null) {
									jsonBuilder.append(line);
								}

								try {
									Class<?> type = method.getParameters()[0].getType();
									Object invoke = method.invoke(ScanUtils.newInstance(aClass), JSON.parseObject(jsonBuilder.toString(), type));
									// 写入JSON数据
									out.print(JSON.toJSONString(invoke));
									// 清空缓冲区，发送数据到客户端
									out.flush();
									// 关闭Writer对象
									out.close();
								} catch (IllegalAccessException e) {
									e.printStackTrace();
								} catch (InvocationTargetException e) {
									e.printStackTrace();
								}

							}
						};
						result.put(method.getAnnotation(RequestMapping.class).value(),jsonHttpServlet);
					}

				}
			}
		}
		return result;
	}



}
